#include "io_context_pool.h"

net_tcp::io_context_pool::io_context_pool(int size) :m_io_contexts(size) {
	m_used_size = 0;
	m_io_context_id = 0;
	m_works.resize(0);
	m_threads.resize(0);
}

asio::io_context& net_tcp::io_context_pool::get_one_context()
{
	if (m_used_size < m_io_contexts.size())
	{
		m_io_context_id = m_used_size++;
		m_works.push_back(std::unique_ptr<asio::io_context::work>(new asio::io_context::work(m_io_contexts[m_io_context_id])));
		int id = m_io_context_id;
		m_threads.emplace_back([this, id]()->void {
			m_io_contexts[id].run();
		});
		return m_io_contexts[m_io_context_id];
	}
	else {
		if (m_io_context_id == m_io_contexts.size())
			m_io_context_id = 0;
		return m_io_contexts[m_io_context_id++];
	}
}

void net_tcp::io_context_pool::reset()
{
	for (auto& work : m_works)
	{
		work.reset();
	}
	for (auto& t : m_threads)
	{
		t.join();
	}
	m_works.resize(0);
	m_threads.resize(0);
	m_used_size = 0;
	m_io_context_id = 0;
}

